package com.jlastu.dlxy_androidapp.view.details;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.jlastu.dlxy_androidapp.R;
import com.jlastu.dlxy_androidapp.contract.GoodsDetailsContract;
import com.jlastu.dlxy_androidapp.entity.Goods;
import com.jlastu.dlxy_androidapp.entity.OrderCart;
import com.jlastu.dlxy_androidapp.entity.Photo;
import com.jlastu.dlxy_androidapp.presenter.GoodsDetailsPresenter;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class CommodityDetails extends AppCompatActivity implements View.OnClickListener, GoodsDetailsContract.IGoodsDetailsView {
    ArrayList<OrderCart> ordercartsList = new ArrayList<>();
    TextView service;
    String locate = "山东省临沂市沂南县湖头镇水由村委会";
//    String productName = "山东红富士苹果";
    String productName;
//    String productDetails = "1斤起售";
    String productDetails;
    private double price;
    Goods goods;
    String type_name = "apple";
    ImageView shop_icons_detail1;
    ImageView shop_icons_detail;
    ImageView shop_icons_xiangqing;
    TextView tit_desc_xiangqing;
    TextView title_text1;
    TextView title_text;
    TextView price_text1;
    TextView price_text;
    TextView total_price_text;
    TextView total_price_text1;
    TextView good_locate;
    Intent intent2;
    ImageView shoucangIcons;
    TextView phoneTextView;
    ImageButton shop_btn1;
    TextView price_xiangqing;
    TextView shop_btn2;
    String type = "apple";
    TextView detail_text1;
    TextView detail_text;
    TextView purchaseButton1;
    TextView purchaseButton;
    String total_pice;
    String good_price;

//    Goods goods1 = new Goods("山东红富士苹果", 29.9, "1斤起售", "山东省临沂市沂南县湖头镇水由村委会", "apple");
    Goods goods1;
//    Goods goods2 = new Goods("山西绿富士西瓜", 58.8, "1斤起售", "山西省运城市临猗县湖尾镇火由村委会", "watermelon");

    private GoodsDetailsContract.IGoodsDetailsPresenter mGoodsDetailsPresenter;

    private List<Goods> mGoodsList;

    private List<Photo> mPhotoList;

    private Integer GoodsID;
    private int store_id;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity_details);
        mGoodsDetailsPresenter = new GoodsDetailsPresenter(this, this);
        mGoodsList = new ArrayList<>();
        mPhotoList = new ArrayList<>();
        Intent intent = getIntent();
        GoodsID = intent.getIntExtra("goods_id", 0);
        Log.d("TAG", "onCreate: " + GoodsID);
        mGoodsDetailsPresenter.getGoodsList(GoodsID);

        initiateView();
        // 购物车获取传递过来的ordercartsList
        Intent intent1 = getIntent();
        if (intent1 != null && intent1.hasExtra("ordercartsList")) {
            if (intent1.hasExtra("type")) type = getIntent().getStringExtra("type");
            if (ordercartsList != null)
                ordercartsList = (ArrayList<OrderCart>) intent1.getSerializableExtra("ordercartsList");
            if (type != null && type.equals("watermelon")) {
                goods = goods1;
            }
            initiate();
        } else {
            ordercartsList = new ArrayList<>();
        }
        //店铺传递过来的商品类型
        intent2 = getIntent();
        if (intent2 != null && intent2.hasExtra("goods")) {
            goods = (Goods) intent2.getSerializableExtra("goods");
            initiate();
        }
        //收藏

        shoucangIcons.setOnClickListener(new View.OnClickListener() {
            boolean isCollected = false;

            @Override
            public void onClick(View v) {
                if (isCollected) {
                    // 图片换成 collect_no
                    shoucangIcons.setImageResource(R.drawable.collect_no);
                    isCollected = false;
                    Toast.makeText(getApplicationContext(), "取消收藏", Toast.LENGTH_SHORT).show();
                } else {
                    // 图片换成 collect_yes
                    shoucangIcons.setImageResource(R.drawable.collect_yes);
                    isCollected = true;
                    Toast.makeText(getApplicationContext(), "收藏成功", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //电话

        phoneTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNumber = "13084953626";
                Uri phoneNumberUri = Uri.parse("tel:" + phoneNumber);
                Intent dialIntent = new Intent(Intent.ACTION_DIAL, phoneNumberUri);
                startActivity(dialIntent);
            }
        });

        //购物车+立即购买
        final boolean[] isPressed = {false};
        Button addCartButton = findViewById(R.id.add_cart_btn);
        Button buy_now = findViewById(R.id.buy_now_btn);
        ConstraintLayout bottomSheet = findViewById(R.id.bottom_sheet);
        ConstraintLayout bottomSheet1 = findViewById(R.id.bottom_sheet1);
        ImageButton shut = findViewById(R.id.shut);
        ImageButton shut1 = findViewById(R.id.shut1);
        BottomSheetBehavior<ConstraintLayout> behavior = BottomSheetBehavior.from(bottomSheet);
        BottomSheetBehavior<ConstraintLayout> behavior1 = BottomSheetBehavior.from(bottomSheet1);
        behavior.setDraggable(false);
        behavior.setHideable(true);
        behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        behavior1.setDraggable(false);
        behavior1.setHideable(true);
        behavior1.setState(BottomSheetBehavior.STATE_HIDDEN);
        addCartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 设置BottomSheet展开状态
                behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
        });
        buy_now.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 设置BottomSheet展开状态
                behavior1.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
        });
        shut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
            }
        });
        shut1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                behavior1.setState(BottomSheetBehavior.STATE_HIDDEN);
            }
        });
        //购物车数量总价变化
        Button minusButton = findViewById(R.id.minus_button);
        Button plusButton = findViewById(R.id.plus_button);
        TextView quantityTextView = findViewById(R.id.quantity_text);
        Button minusButton1 = findViewById(R.id.minus_button1);
        Button plusButton1 = findViewById(R.id.plus_button1);
        TextView quantityTextView1 = findViewById(R.id.quantity_text1);
        // 初始化数量和单价的值
        final int[] quantity = {1};
        // 设置减号按钮点击事件监听器
        minusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (quantity[0] > 1 && !isPressed[0]) {
                    quantity[0]--;
                    quantityTextView.setText(String.valueOf(quantity[0]));
                    double totalPrice = quantity[0] * price;
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    String formattedPrice = decimalFormat.format(totalPrice);
                    total_price_text.setText("总价：¥" + formattedPrice);
                }
            }
        });
        minusButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (quantity[0] > 1 && !isPressed[0]) {
                    quantity[0]--;
                    quantityTextView1.setText(String.valueOf(quantity[0]));
                    double totalPrice = quantity[0] * price;
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    String formattedPrice = decimalFormat.format(totalPrice);
                    total_price_text1.setText("总价：¥" + formattedPrice);
                }
            }
        });

        // 设置加号按钮点击事件监听器
        plusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isPressed[0]) {
                    quantity[0]++;
                    quantityTextView.setText(String.valueOf(quantity[0]));
                    double totalPrice = quantity[0] * price;
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    String formattedPrice = decimalFormat.format(totalPrice);
                    total_price_text.setText("总价：¥" + formattedPrice);
                }

            }
        });
        plusButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isPressed[0]) {
                    quantity[0]++;
                    quantityTextView1.setText(String.valueOf(quantity[0]));
                    double totalPrice = quantity[0] * price;
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    String formattedPrice = decimalFormat.format(totalPrice);
                    total_price_text1.setText("总价：¥" + formattedPrice);
                }

            }
        });
        //选择细类
        purchaseButton = findViewById(R.id.purchase_Button);
        purchaseButton1 = findViewById(R.id.purchase_Button1);


        purchaseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isPressed[0]) {
                    // 更改样式
                    purchaseButton.setTextColor(getResources().getColor(android.R.color.black));
                    purchaseButton.setBackground(getResources().getDrawable(R.drawable.gray_border));
                    quantity[0] = 0;
                    quantityTextView.setText(String.valueOf(quantity[0]));
                    total_price_text.setText("总价：¥0.00");
                } else {
                    // 恢复原样式
                    purchaseButton.setTextColor(getResources().getColor(R.color.orange));
                    purchaseButton.setBackground(getResources().getDrawable(R.drawable.orange_border));
                }
                isPressed[0] = !isPressed[0]; // 切换状态
            }
        });
        purchaseButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isPressed[0]) {
                    // 更改样式
                    purchaseButton.setTextColor(getResources().getColor(android.R.color.black));
                    purchaseButton.setBackground(getResources().getDrawable(R.drawable.gray_border));
                    quantity[0] = 0;
                    quantityTextView1.setText(String.valueOf(quantity[0]));
                    total_price_text1.setText("总价：¥0.00");
                } else {
                    // 恢复原样式
                    purchaseButton.setTextColor(getResources().getColor(R.color.orange));
                    purchaseButton.setBackground(getResources().getDrawable(R.drawable.orange_border));
                }
                isPressed[0] = !isPressed[0]; // 切换状态
            }
        });
        //点击添加购物车 创建购物车订单
        Button buyButton = findViewById(R.id.buy_button);
        ImageView car_icons = findViewById(R.id.car_icons);
        car_icons.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CommodityDetails.this, Cart.class);
                intent.putExtra("ordercartsList", ordercartsList);
                intent.putExtra("type", type);
                Log.d("TAG", "ordercartsList: "+ordercartsList);
                Log.d("TAG", "type: "+type);
                startActivity(intent);
            }
        });
        buyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取表单信息
                int quantity = Integer.parseInt(quantityTextView.getText().toString());
                double totalPrice = Double.parseDouble(total_price_text.getText().toString().substring(4));
                // 获取订单时间
                Date currentDate = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss", Locale.CHINA);
                String formattedTime = dateFormat.format(currentDate);

                int id;
                if (productName.equals("山东红富士苹果")) {
                    id = 1;
                } else id = 2;
                // 创建 Order 对象
                OrderCart order = new OrderCart(productName, productDetails, quantity, totalPrice, formattedTime, id, locate);
                // 将订单对象添加到订单列表
                ordercartsList.add(order);
                // 显示添加成功的提示
                showAddSuccessToast();


            }
        });
        //立即购买
        Button buyButton1 = findViewById(R.id.buy_button1);
        buyButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取表单信息
                int quantity = Integer.parseInt(quantityTextView1.getText().toString());
                double totalPrice = Double.parseDouble(total_price_text1.getText().toString().substring(4));
                // 获取订单时间
                Date currentDate = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss", Locale.CHINA);
                String formattedTime = dateFormat.format(currentDate);

                int id;
                if (productName.equals("山东红富士苹果")) {
                    id = 1;
                } else id = 2;
                // 创建 Order 对象
                OrderCart order = new OrderCart(productName, productDetails, quantity, totalPrice, formattedTime, id, locate);
                // 将订单对象添加到订单列表
                if (ordercartsList == null) {
                    ordercartsList = new ArrayList<>();
                }
                ordercartsList.add(order);
                Intent intent = new Intent(CommodityDetails.this, OrderActivity.class);
                intent.putExtra("ordercartsList", ordercartsList);
                startActivity(intent);


            }
        });

        //客服
        service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CommodityDetails.this, Service.class);
                startActivity(intent);
            }
        });
        //店铺
        shop_btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shop();
            }
        });
        shop_btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shop();
            }
        });

    }

    private void showAddSuccessToast() {
        Toast.makeText(CommodityDetails.this, "添加购物车成功", Toast.LENGTH_SHORT).show();
    }

    private void initiate() {
        productName = goods.getName();
        if (productName.equals("山西绿富士西瓜")) {
            type = "watermelon";
        }
        locate = goods.getLocate();
        good_locate.setText(goods.getLocate());
    }

    private void initiateView() {
//        单价
        price_xiangqing = findViewById(R.id.price_xiangqing);
        shop_btn1 = findViewById(R.id.shop_btn1);
        shop_btn2 = findViewById(R.id.shop_btn2);
        service = findViewById(R.id.kefu_tv);
        shoucangIcons = findViewById(R.id.shoucang_icons);
        //        购物车
        shop_icons_detail = findViewById(R.id.shop_icons_detail);
        //        购买
        shop_icons_detail1 = findViewById(R.id.shop_icons_detail1);
//        大图
        shop_icons_xiangqing = findViewById(R.id.shop_icons_xiangqing);

        title_text1 = findViewById(R.id.title_text1);
        title_text = findViewById(R.id.title_text);
//        名字
        tit_desc_xiangqing = findViewById(R.id.tit_desc_xiangqing);
//        购买
        price_text1 = findViewById(R.id.price_text1);
//        购物车
        price_text = findViewById(R.id.price_text);
//                购物车
        total_price_text = findViewById(R.id.total_price_text);
//                购买
        total_price_text1 = findViewById(R.id.total_price_text1);
        good_locate = findViewById(R.id.fa_text);
        phoneTextView = findViewById(R.id.phone_tv);
        detail_text1 = findViewById(R.id.detail_text1);
        detail_text = findViewById(R.id.detail_text);
    }

    private void shop() {
        Intent intent = new Intent(CommodityDetails.this, StoreActivity.class);
        intent.putExtra("store_id", store_id);
        startActivity(intent);

    }


    @Override
    public void onClick(View v) {

    }

    @SuppressLint({"SetTextI18n", "DefaultLocale"})
    @Override
    public void showGoodsList(List<Goods> goodsList, List<Photo> photoList) {
        mGoodsList = goodsList;
        mPhotoList = photoList;

        Log.d("", "showGoodsList " + mGoodsList.size());
//        mSelectRecyclerAdapter.updateData(mGoodsList , mPhotoList);
        for (Photo photo : mPhotoList) {
            shop_icons_xiangqing.setImageBitmap(photo.getBitmap());
            shop_icons_detail.setImageBitmap(photo.getBitmap());
            shop_icons_detail1.setImageBitmap(photo.getBitmap());
        }
        for (Goods goods : mGoodsList) {
            productName = goods.getName();
            type_name = goods.getClassify();
            productDetails = goods.getUnit();
            price_xiangqing.setText(String.format("%.2f/%s", goods.getPrice(), goods.getUnit()));
            price = goods.getPrice();
            price_text.setText(String.format("%.2f/%s", goods.getPrice(), goods.getUnit()));
            price_text1.setText(String.format("%.2f/%s", goods.getPrice(), goods.getUnit()));
            tit_desc_xiangqing.setText(productName);
            detail_text1.setText("1"+goods.getUnit()+"起售");
            detail_text.setText("1"+goods.getUnit()+"起售");
            purchaseButton.setText("1"+goods.getUnit());
            purchaseButton1.setText("1"+goods.getUnit());
            title_text.setText(goods.getName());
            title_text1.setText(goods.getName());
            total_price_text.setText(String.format("总价：¥" + goods.getPrice()));
            total_price_text1.setText(String.format("总价：¥" + goods.getPrice()));
            store_id = goods.getStore_id();
            goods1 = new Goods(goods.getName(), goods.getPrice(), goods.getMessage(), "山东省临沂市沂南县湖头镇水由村委会", goods.getClassify());
        }


    }
}